//
//  AppDelegate.m
//  1gene
//
//  Created by 1jiyin on 16/2/26.
//  Copyright © 2016年 1jiyin. All rights reserved.
//

#import "AppDelegate.h"
#import "UMSocial.h"
#import "UMSocialQQHandler.h"
#import "UMSocialWechatHandler.h"
#import "UMSocialSinaSSOHandler.h"
#import "UMSocialSinaHandler.h"
#import <RongIMKit/RongIMKit.h>
#import <AlipaySDK/AlipaySDK.h>
#import "IsFirstUseAppViewController.h"

#define kCueentUserImageUrl [[NSUserDefaults standardUserDefaults]objectForKey:@"userHeadImage"]

@interface AppDelegate ()<RCIMUserInfoDataSource,RCIMGroupInfoDataSource, RCIMConnectionStatusDelegate, UIAlertViewDelegate>

@property (nonatomic, assign) BOOL isFirstShowQuitAlert; // 是否是第一次显示下线提醒框

@end
@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window=[[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor=[UIColor whiteColor];
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    NSString *phone=[user objectForKey:@"userPhone"];
    NSString *password=[user objectForKey:@"userPassword"];
    NSLog(@"手机号：%@，密码：%@", phone, password);
    if (phone == nil && password == nil) {
        NSLog(@"为空");
    }
    BOOL isFirstUseApp=[user objectForKey:@"firstUseApp"];
    if (isFirstUseApp) {
        if (phone.length>0&&password.length>0) {
            [self showMainViewController:0];
        }else{
            [self showMainViewController:0];
        }
    }else{
        //[self firstUseApp];
        self.window.rootViewController=[IsFirstUseAppViewController new];
    }
    
    
    
    [[UIApplication sharedApplication]setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
   // 融云的一些设置
    [self configOfRongCloud];
   
    
    [UMSocialData setAppKey:@"507fcab25270157b37000010"];
    [UMSocialQQHandler setQQWithAppId:@"100424468" appKey:@"c7394704798a158208a74ab60104f0ba" url:@"http://www.umeng.com/social"];
    [UMSocialWechatHandler setWXAppId:@"wxd930ea5d5a258f4f" appSecret:@"db426a9829e4b49a0dcac7b4162da6b6" url:@"http://www.umeng.com/social"];
    //[UMSocialSinaSSOHandler openNewSinaSSOWithAppKey:@"3921700954" RedirectURL:@"http://sns.whalecloud.com/sina2/callback"];
    //[UMSocialSinaHandler openSSOWithRedirectURL:@"http://sns.whalecloud.com/sina2/callback"];
    //[UMSocialConfig hiddenNotInstallPlatforms:@[UMShareToQQ, UMShareToQzone, UMShareToWechatSession, UMShareToWechatTimeline]];
    // Override point for customization after application launch.
//    if ([[UIApplication sharedApplication]currentUserNotificationSettings].types!=UIUserNotificationTypeNone) {
//    }else{
//        [[UIApplication sharedApplication]registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound  categories:nil]];
//    }
//    
    //[NSThread sleepForTimeInterval:10.0];//设置启动页面时间
    
    return YES;
}


-(void)myClearCacheAction
{
    
    
}

// 融云的一些设置
- (void)configOfRongCloud
{
    
  //  [[RCIM sharedRCIM] initWithAppKey:@"p5tvi9dstslt4"]; // 192本地测试
  //  [[RCIM sharedRCIM] initWithAppKey:@"qf3d5gbj3uwdh"]; // 120开发环境上线的
    [[RCIM sharedRCIM] initWithAppKey:@"sfci50a7c23ii"]; // 120生产环境
    [[RCIM sharedRCIM] setUserInfoDataSource:self];
    [[RCIM sharedRCIM] setGroupInfoDataSource:self];
    [[RCIM sharedRCIM] setConnectionStatusDelegate:self];
    [RCIM sharedRCIM].enableTypingStatus = YES; // 开启正在输入的功能，目前只支持单聊
}



-(void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings{
    if (notificationSettings.types!=UIUserNotificationTypeNone) {
        
    }
}

-(void)removeNotification{
    [[UIApplication sharedApplication] cancelAllLocalNotifications];
}

-(void)showMainViewController:(NSInteger)state
{
    if (state==0) {
        UINavigationController *vc=[[UINavigationController alloc]initWithRootViewController:[[MainViewController alloc]init]];
        self.window.rootViewController=vc;
    }else{
        // 每次显示首页的时候都可以显示提醒退出app的框
        self.isFirstShowQuitAlert = YES;
         NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
        NSString *rong_token=[user objectForKey:@"rong_token"];
        
        NSString *tiaoguo=[user objectForKey:@"tiaoguo"];
        if ([tiaoguo isEqualToString:@"tiaoguo"]) {
            [self.window isLoading:NO];
            _vc=[[CustomViewController alloc]init];
            self.window.rootViewController=_vc;
            [user setObject:@"" forKey:@"tiaoguo"];
        }else{
            [self.window isLoading:NO];
            dispatch_async(dispatch_get_main_queue(), ^{
                _vc=[[CustomViewController alloc]init];
                self.window.rootViewController=_vc;
                [user setObject:@"" forKey:@"tiaoguo"];
            });
            
            
            [[RCIM sharedRCIM]connectWithToken:rong_token success:^(NSString *userId) {
                NSLog(@"登陆成功。当前登录的用户ID：%@", userId);
                NSLog(@"当前用户头像:%@", kCueentUserImageUrl);
                // 保存当前登陆融云的用户ID
                [[NetStatusHandle shareHandle] saveCurrentLoginRongCloudUserID:userId];
                // 融云登录成功
                [[NetStatusHandle shareHandle] saveLoginRCloudIsSuccess:@"YES"];
            } error:^(RCConnectErrorCode status) {
               // [self.window showTiShiMessage:@"登陆失败"];
                NSLog(@"登陆融云的错误码为:%ld", status);
                // 融云登录失败
                [[NetStatusHandle shareHandle] saveLoginRCloudIsSuccess:@"NO"];
            } tokenIncorrect:^{
                //[self.window showTiShiMessage:@"登陆失败"];
                //token过期或者不正确。
                //如果设置了token有效期并且token过期，请重新请求您的服务器获取新的token
                //如果没有设置token有效期却提示token错误，请检查您客户端和服务器的appkey是否匹配，还有检查您获取token的流程。
                NSLog(@"token错误");
                // 融云登录失败
                [[NetStatusHandle shareHandle] saveLoginRCloudIsSuccess:@"NO"];
            }];
        }
    }
}

- (void)onRCIMConnectionStatusChanged:(RCConnectionStatus)status
{
//    if (status == ConnectionStatus_KICKED_OFFLINE_BY_OTHER_CLIENT) {
//        NSLog(@"您的账号被迫下线");
//    }
//    NSLog(@"错误原因:%ld", (long)status);
    if (status == ConnectionStatus_UNKNOWN) {
//        NSLog(@"您的账号被迫下线");
//        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"警告" message:@"您的账号在别处登陆，您被迫下线" preferredStyle:UIAlertControllerStyleAlert];
//        // 修改标题颜色
//        NSMutableAttributedString *title = [[NSMutableAttributedString alloc] initWithString:@"警告"];
//        [title addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 2)];
//        [title addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:17] range:NSMakeRange(0, 2)];
//        [alertVC setValue:title forKey:@"attributedTitle"];
//        
//        UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//            
//        }];
//        [alertVC addAction:sureAction];
//        UIAlertAction *chongXinDengLuAction = [UIAlertAction actionWithTitle:@"重新登陆" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//            
//        }];
//        [alertVC addAction:chongXinDengLuAction];
    
        
        if (self.isFirstShowQuitAlert == YES) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提醒" message:@"新的账号在别的设备上登录，您被迫下线！" delegate:self cancelButtonTitle:@"重新登录" otherButtonTitles:@"知道了", nil];
            [alertView show];
        }
        self.isFirstShowQuitAlert = NO;
    }
}

#pragma mark - alertView代理
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        NSLog(@"重新登陆");
        [self quitApp];
    } else if (buttonIndex == 1) {
        NSLog(@"确定");
        [self quitApp];
    }
}

// 退出客户端
- (void)quitApp
{
    AFHTTPRequestOperationManager *manager=[AFHTTPRequestOperationManager manager];
    manager.requestSerializer=[AFHTTPRequestSerializer serializer];
    manager.responseSerializer=[AFHTTPResponseSerializer serializer];
    [self.window isLoading:YES];
    
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    NSString *token= [user objectForKey:@"token"];
    NSLog(@"token=======%@",token);
    [manager GET:[NSString stringWithFormat:@"%@%@",LogOut,token] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"login=======%@",dic);
        if (dic) {
            NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
            [user setObject:nil forKey:@"token"];
            [user setObject:nil forKey:@"userId"];
            [user setObject:nil forKey:@"userName"];
            [user setObject:nil forKey:@"userPhone"];
            [user setObject:nil forKey:@"userPassword"];
            [user setObject:nil forKey:@"rong_token"];
            [user synchronize];
            [[RCIM sharedRCIM]logout];
             [[NetStatusHandle shareHandle] saveLoginRCloudIsSuccess:@"NO"];
            dispatch_async(dispatch_get_main_queue(), ^{
        
                [self showMainViewController:0];
            });
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self.window isLoading:NO];
        //[self.view showTiShiMessage:@"退出失败"];
        NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
        [user setObject:nil forKey:@"token"];
        [user setObject:nil forKey:@"userId"];
        [user setObject:nil forKey:@"userName"];
        [user setObject:nil forKey:@"userPhone"];
        [user setObject:nil forKey:@"userPassword"];
        [user setObject:nil forKey:@"rong_token"];
        [user synchronize];
        [[RCIM sharedRCIM]logout];
         [[NetStatusHandle shareHandle] saveLoginRCloudIsSuccess:@"NO"];
        dispatch_async(dispatch_get_main_queue(), ^{
           
            [self showMainViewController:0];
        });
        
        NSLog(@"error====%@",error.localizedDescription);
    }];

}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    BOOL result = [UMSocialSnsService handleOpenURL:url];
    if (result == FALSE) {
        //调用其他SDK，例如支付宝SDK等
        return result;
    }
    else if ([url.host isEqualToString:@"safepay"]) {
        //跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
        }];
    }
    return YES;
    //
}



- (void)getUserInfoWithUserId:(NSString *)userId completion:(void (^)(RCUserInfo *))completion{
//    NSUserDefaults *myUser=[NSUserDefaults standardUserDefaults];
//    NSString *currentUserId=[NSString stringWithFormat:@"%@",[myUser objectForKey:@"userId"]];
//    NSString *currentUserName=[myUser objectForKey:@"userName"];
//    NSString *currentUserHeadImage=[myUser objectForKey:@"userHeadImage"];
//    
//    
//    
//    NSLog(@"方法执行1====userid=%@====currentUserid=%@",userId,currentUserId);
//    [[RCIM sharedRCIM] clearUserInfoCache];
//    if ([currentUserId isEqualToString:userId]) {
//        RCUserInfo *user = [[RCUserInfo alloc]init];
//        user.userId = currentUserId;
//        user.name = currentUserName;
//        user.portraitUri = currentUserHeadImage;
//        NSLog(@"方法执行2===%@",currentUserHeadImage);
//        [[RCIM sharedRCIM]refreshUserInfoCache:user withUserId:currentUserId];
//        return completion(user);
//        
//    }
//    
//    //            [user setObject:_userDic[@"user_profile"][@"user_id"] forKey:@"otherUserId"];
//    //            [user setObject:_userDic[@"user_profile"][@"nikename"] forKey:@"otherUserName"];
//    //            [user setObject:_userDic[@"user_profile"][@"avatar_url"] forKey:@"otherUserHeadImage"];
//    
//    NSArray *myDefaultsArray=[myUser objectForKey:@"myDefaultsArray"];
//    for (NSDictionary *myDefaultsDic in myDefaultsArray) {
//        NSString *otherUserId=[NSString stringWithFormat:@"%@",myDefaultsDic[@"otherUserId"]];
//        NSString *otherUserName=myDefaultsDic[@"otherUserName"];
//        NSString *otherUserHeadImage=myDefaultsDic[@"otherUserHeadImage"];
//        if ([otherUserId isEqualToString:userId]) {
//            RCUserInfo *user = [[RCUserInfo alloc]init];
//            user.userId = otherUserId;
//            user.name = otherUserName;
//            user.portraitUri = otherUserHeadImage;
//            NSLog(@"方法执行3=====%@",otherUserHeadImage);
//            [[RCIM sharedRCIM]refreshUserInfoCache:user withUserId:otherUserId];
//            return completion(user);
//        }
//    }
    NSString *userSampleMessage = [NSString stringWithFormat:@"%@%@", kZGWGetUserSampleMessageByUserID, userId];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:userSampleMessage parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        NSDictionary *statusDic = [responseObject valueForKey:@"status"];
        NSString *codeString = [NSString stringWithFormat:@"%@", [statusDic valueForKey:@"code"]];
        if ([codeString isEqualToString:@"0"]) {
            // 说明有用户信息
            NSDictionary *userDic = [responseObject valueForKey:@"user"];
            RCUserInfo *user = [[RCUserInfo alloc] init];
            user.userId = [userDic valueForKey:@"user_id"];
            user.name = [userDic valueForKey:@"nikename"];
            user.portraitUri = [userDic valueForKey:@"avatar_url"];
          //  [[RCIM sharedRCIM] refreshUserInfoCache:user withUserId:userId];
            return completion(user);
        } else {
            return completion(nil);
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
          return completion(nil);
    }];

    

    return completion(nil);
}
- (void)getGroupInfoWithGroupId:(NSString *)groupId completion:(void (^)(RCGroup *))completion
{
    
}
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
  //   [[SDImageCache sharedImageCache] clearDisk];
    
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    NSLog(@"deviceToken======%@",deviceToken);
}

@end
